<template>
	<view class="container">
		<!-- 地图组件 -->
		<map id="navigationMap" :latitude="center.lat" :longitude="center.lng" :polyline="polyline" :markers="markers"
			:circles="circles" :include-points="includePoints" :show-location="true" style="width: 100%; height: 100vh;"
			@regionchange="onRegionChange" @click="handleMapClick" 
			></map>
		<!-- 新增地图点击事件 -->
		<!-- 控制面板 -->
		<view class="control-panel">
			<button @click="startNavigation" :disabled="!isNavigating">开始导航</button>
			<button @click="clearRoute">清除路线</button>
			<view class="waypoints">
				<text>途径点 ({{ waypoints.length }})</text>
				<button v-for="(wp, index) in waypoints" :key="index" @click="removeWaypoint(index)">
					{{ wp.name || '未命名' }} <!-- 显示途径点名称 -->
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '@/utils/qqmap-wx-jssdk.js' // 确保正确引入SDK

	export default {
		data() {
			return {
				center: {
					lat: 39.90923,
					lng: 116.397428
				},
				dest: null, // 新增目的地数据
				markers: [],
				polyline: [],
				circles: [],
				includePoints: [],
				waypoints: [{
						lat: 39.9123,
						lng: 116.3945,
						name: '途径点1'
					},
					{
						lat: 39.9056,
						lng: 116.3898,
						name: '途径点2'
					}
				],
				isNavigating: false,
				routeData: null,
				locationTask: null // 新增位置更新任务管理
			}
		},
		mounted() {
			this.initMap();
			this.getCurrentLocation();
		},
		methods: {
			// 初始化地图
			initMap() {
				// 保留初始标记但避免重复添加
				if (!this.markers.find(m => m.id === 1)) {
					this.markers.push({
						id: 1,
						latitude: this.center.lat,
						longitude: this.center.lng,
						// iconPath: '/static/current.png', // 假设存在此图标
						width: 30,
						height: 30
					});
				}
			},

			// 获取当前位置（修复错误处理）
			async getCurrentLocation() {
				try {
					const res = await uni.getLocation({
						type: 'gcj02',
						geocode: true // 同时获取地址信息
					});

					this.center = {
						lat: res.latitude,
						lng: res.longitude
					};

					// 更新当前位置标记
					this.updateCurrentMarker(res);

					// 自动规划路线到当前位置
					this.calculateRoute();
				} catch (err) {
					uni.showToast({
						title: '定位失败',
						icon: 'none'
					});
				}
			},

			// 更新当前位置标记
			updateCurrentMarker(location) {
				const marker = this.markers.find(m => m.id === 1);
				if (marker) {
					marker.latitude = location.latitude;
					marker.longitude = location.longitude;
				} else {
					this.markers.push({
						id: 1,
						...location,
						// iconPath: '/static/current.png'
					});
				}
			},

			// 处理地图点击事件（新增）
			handleMapClick(e) {
				// 添加点击位置的途径点
				this.waypoints.push({
					lat: e.latitude,
					lng: e.longitude,
					name: `途经点${this.waypoints.length + 1}`
				});
				this.calculateRoute();
			},

			// 路线规划（修复dest未定义问题）
			async calculateRoute() {
				if (!this.dest) return; // 需要先设置目的地

				try {
					const url =
						`https://apis.map.qq.com/ws/direction/v1/driving/?from=${encodeURIComponent(this.center.lat)},${encodeURIComponent(this.center.lng)}&to=${encodeURIComponent(this.dest.lat)},${encodeURIComponent(this.dest.lng)}&waypoints=${encodeURIComponent(this.waypoints.map(p => `${p.lat},${p.lng}`).join(';'))}&key=WRMBZ-RM7YJ-URSFC-XPNQY-PTF56-HDB4S`;

					const res = await uni.request({
						url
					});

					if (res.data.status === 0) {
						this.routeData = res.data.result.routes[0];
						this.drawRoute();
						this.startRealTimeUpdate();
					} else {
						uni.showToast({
							title: '路线规划失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('路线规划错误:', err);
					uni.showToast({
						title: '服务异常',
						icon: 'none'
					});
				}
			},

			// 绘制路线（优化解码）
			drawRoute() {
				if (!this.routeData) return;

				// 使用正确解码方法
				const polyline = this.qqmapPolylineDecode(this.routeData.polyline);
				this.polyline = [{
					points: polyline,
					color: '#FF0000DD',
					width: 6,
					dottedLine: false
				}];
			},

			// 腾讯地图标准解码方法
			qqmapPolylineDecode(str) {
				let index = 0,
					len;
				if (str === null || str === '') return [];
				len = str.length;
				let points = [];
				let lat = 0,
					lng = 0;
				while (index < len) {
					let b, shift = 0,
						result = 0;
					do {
						b = str.charCodeAt(index++) - 63;
						result |= (b & 0x1f) << shift;
						shift += 5;
					} while (b >= 0x20);
					let dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
					lat += dlat;

					shift = 0;
					result = 0;
					do {
						b = str.charCodeAt(index++) - 63;
						result |= (b & 0x1f) << shift;
						shift += 5;
					} while (b >= 0x20);
					let dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
					lng += dlng;

					points.push({
						latitude: lat * 1E-5,
						longitude: lng * 1E-5
					});
				}
				return points;
			},

			// 实时位置更新（完善逻辑）
			startRealTimeUpdate() {
				if (this.locationTask) return;

				this.locationTask = uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						this.updateCurrentMarker(res);
						this.updateRoute(res);
					},
					fail: () => {
						uni.showToast({
							title: '定位失败',
							icon: 'none'
						});
					}
				});
			},

			// 更新路线（动态偏移）
			updateRoute(location) {
				if (!this.routeData) return;

				// 这里可以添加动态偏移计算逻辑
				// 示例仅更新当前位置标记
				this.includePoints = [location];
			},

			// 清除路线（增强清理）
			clearRoute() {
				this.polyline = [];
				this.markers = this.markers.filter(m => m.id !== 1); // 保留初始标记
				this.waypoints = [];
				this.dest = null;
				this.isNavigating = false;
				if (this.locationTask) {
					uni.stopLocationUpdate({
						success: () => this.locationTask = null
					});
				}
			},

			// 开始导航（示例跳转）
			startNavigation() {
				if (!this.dest) {
					uni.showToast({
						title: '请先选择目的地',
						icon: 'none'
					});
					return;
				}

				uni.navigateTo({
					url: `/pages/navigator/navigator?routeData=${encodeURIComponent(JSON.stringify(this.routeData))}`
				});
			}
		},
		onUnload() {
			// 页面卸载时清理任务
			if (this.locationTask) {
				uni.stopLocationUpdate({
					success: () => this.locationTask = null
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		position: relative;
	}

	.control-panel {
		position: fixed;
		bottom: 20px;
		left: 0;
		right: 0;
		background: white;
		padding: 15px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		z-index: 1000;
	}

	.waypoints {
		margin-top: 10px;
		display: flex;
		flex-direction: column;
	}

	button {
		margin: 5px;
		padding: 8px 15px;
		background: #007AFF;
		color: white;
		border: none;
		border-radius: 5px;
	}

	button:disabled {
		background: #CCCCCC;
	}
</style>